// ---------------------------------------------------------------------------
// This software is in the public domain, furnished "as is", without technical
// support, and with no warranty, express or implied, as to its usefulness for
// any purpose.
//
// BencodingHandler.C
// BencodingData class and some BencodingData handler funcs.
//
// Author: wuwei0509@gmail.com
// ---------------------------------------------------------------------------

#include <assert.h>
#include "Helper.h"
#include "BencodingHandler.h"


#define INTSPACE 65

string BencodingHandler::ReadString(char * seedContent, __int64& startPos)
{
	assert(seedContent != NULL);
	assert(startPos >= 0);

	char * head = seedContent + startPos;
	char * intSpace = Helper::mallocSpace(INTSPACE);
	char * intSpaceHead = intSpace;
	__int64 len = 0;
	char delimiter = L':';//':'
	char * value = NULL;
	//get string length
	while(*head != delimiter){
		*(intSpaceHead++) = static_cast<char>(*(head++));
		startPos ++;
	}
	//jump over ':'
	head++;
	startPos++;
	len = _atoi64(intSpace);
	//allocate buffer
	if(len >= 0){
		value = Helper::mallocSpace(len + 1);//one more for '\0'
	}
	cout<<len<<':';
	//read string
	memcpy(value, head, static_cast<size_t>(len));
	head += len;
	startPos += len;

	//clear and return
	string retValue(value);
	cout<<retValue<<endl;
	delete [] intSpace;
	delete [] value;
	return retValue;
}

__int64 BencodingHandler::ReadInt(char * seedContent, __int64& startPos)
{
	assert(seedContent != NULL);
	assert(startPos >= 0);
	
	char * head = seedContent + startPos;
	__int64 value = 0;
	char * intSpace = Helper::mallocSpace(INTSPACE);
	char * intSpaceHead = intSpace;

	if(*(head) == 'i'){
		head++;
		startPos++;
		if(*head == '-' && *(head + 1) == '0'){
			cerr<<"Error: Invalid Bencoding int format! "<<endl;
			exit(1);
		}
		if(*head == '0' && *(head + 1) != 'e'){
			cerr<<"Error: Invalid Bencoding int format! "<<endl;
			exit(1);
		}

		while(*head != 'e'){
			*(intSpaceHead++) = *(head++);
			startPos++;
		}
	} else {
		cerr<<"Error: Invalid Bencoding int format!"<<endl;
		exit(1);
	}

	value = _atoi64(intSpace);
	startPos++;
	cout<<value<<endl;
	delete [] intSpace;
	return value;
}